package data

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type GeneralRepo struct{}

type AdDto struct {
	PicUrl  string `orm:"column(pic_url)"`
	HtmlUrl string `orm:"column(html_url)"`
	SortNum int    `orm:"column(sort_num)"`
}

type DeviceDto struct {
	Id       int64  `orm:"pk;auto;column(id)"`
	ClientId string `orm:"column(client_id)"`
	Profile  string `orm:"column(profile)"`
}

type ClientLogDto struct {
	Id       int    `orm:"column(id)"`
	Name     string `orm:"column(name)"`
	Message  string `orm:"column(message)"`
	Stack    string `orm:"column(stack_trace)"`
	ServerIp string `orm:"column(server_ip)"`
	Time     string `orm:"column(create_time)"`
}

func init() {
	orm.RegisterModel(new(DeviceDto), new(ClientLogDto))
}

func (c *DeviceDto) TableName() string {
	return "k_device"
}

func (c *ClientLogDto) TableName() string {
	return "s_log_exception"
}

func (g GeneralRepo) GetDicts() []orm.ParamsList {
	var lists []orm.ParamsList
	o := orm.NewOrm()
	_, _ = o.Raw(SQL_General_Get_Dicts).ValuesList(&lists)
	return lists
}

func (g GeneralRepo) GetParas() []orm.ParamsList {
	var lists []orm.ParamsList
	o := orm.NewOrm()
	_, _ = o.Raw(SQL_General_Get_Paras).ValuesList(&lists)
	return lists
}

func (g GeneralRepo) GetAds(pageSize int) (list []AdDto) {
	o := orm.NewOrm()
	_, _ = o.Raw(fmt.Sprintf(SQL_General_Get_Ads, pageSize)).QueryRows(&list)
	return
}

func (g GeneralRepo) AddClientId(clientId, profile string) (err error) {
	var num int64
	var list orm.ParamsList
	o := orm.NewOrm()
	if num, err = o.Raw(SQL_General_Check_ClientId_Exists, clientId).ValuesFlat(&list); num == 0 && err == nil {
		_, err = o.Insert(&DeviceDto{ClientId: clientId, Profile: profile})
	}
	return err
}

func (g GeneralRepo) AddClientErrorLogs(list []ClientLogDto) error {
	o := orm.NewOrm()
	_, err := o.InsertMulti(50, list)
	return err
}
